package com.example.campuslink.commen.core

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.example.campuslink.viewModel.BaseViewModel

abstract class CoreAdapter<V : ViewDataBinding, VM : BaseViewModel, T>(
    private val dataId: Int,
    private val vmId: Int = 0,
    protected val mViewModel: VM? = null
) : RecyclerView.Adapter<CoreViewHolder>() {

    var mListData = listOf<T>()


    protected abstract fun getItemLayoutId(viewType: Int): Int

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CoreViewHolder {
        mViewModel?.initDB(parent.context)
        val mViewDataBinding = DataBindingUtil.inflate<V>(
            LayoutInflater.from(parent.context),
            getItemLayoutId(viewType), parent, false
        )
        return CoreViewHolder(mViewDataBinding)
    }

    override fun onBindViewHolder(holder: CoreViewHolder, position: Int) {
        if (vmId != 0 && mViewModel != null) {
            holder.binding.setVariable(vmId, mViewModel)
        }
        if (dataId != 0) {
            holder.binding.setVariable(dataId, mListData[position])
        }
    }

    override fun getItemCount(): Int = mListData.size

    open fun setListData(listData: List<T>) {
        mListData = listData
        notifyDataSetChanged()
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    open fun clear() {
        mListData = listOf()
        notifyDataSetChanged()
    }


    open fun addListData(listData: List<T>) {
        val start = mListData.size
        val newData = listData.filterNot { it in mListData } // 过滤重复数据
        if (newData.isNotEmpty()) {
            mListData = mListData + newData
            notifyDataSetChanged() // 使用插入通知
        }
    }


}